const { logger } = require("../setting/setting.js");
const mysql = require("mysql");

//数据库连接池参数
const mysqlConf = {
  host: "localhost",
  port: "3306",
  user: "root",
  password: "123456",
  database: "xdqblog",
  connectTimeout: 5000,
  multipleStatements: false,
  charset:"UTF8MB4"
};

let dbobject = {
  //数据库连接状态
  db: null,
  //定时ping数据库
  pingInterval: null,
  //错误方法
  handleError: function (errormessage, error) {
    let message = errormessage || "Mysql Occurred";
    let err = error || "in db's on method ";
    logger.publicerror(message,err);
    setTimeout(this.connect, 2000);
  },
  //连接方法
  connect: function () {
    if (this.db != null) {
      this.db.destroy();
      this.db = null;
    }
    
    try{
      this.db = mysql.createConnection(mysqlConf);
      if(this.db!=null){
        this.db.connect((error) => {
          if (error) {
            this.handleError("Mysql Connect", error);
          }
        });
  
        this.db.on("error", this.handleError);
      }
    }
    catch(error){
      throw error
    }
    
    clearInterval(this.pingInterval);
    //每隔一小时Ping一次数据库，保持连接状态
    this.pingInterval = setInterval(() => {
      console.log("mysql is ping...");
      this.db.ping((error) => {
        if (error) {
          this.handleError("Mysql Ping", JSON.stringify(error));
          throw error;
        }
      });
    }, 36000000);
  },
};
dbobject.connect();

module.exports = {
  dbobject,
};
